﻿/*
 * 文件名称：快速添加栏目
 * 程序员：yhe
 * 创建时间：2009-09-11
 * 
 * 功能说明：快速添加栏目管理
 * 
 * 修改记录：
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Whir.Common.WebHelper;
using System.Collections.Generic;

public partial class Whir_System_Module_Role_AddColumn3 : System.Web.UI.Page
{
    /// <summary>
    /// 当前操作
    /// </summary>
    protected string Action = "";
    /// <summary>
    /// 当前栏目编号
    /// </summary>
    protected int ColumnID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        RoleHelper.IsLogin();    //登录判断
        Action = NetRequest.GetQueryString("Action");
        ColumnID = NetRequest.GetQueryInt("ColumnID");

        if (Action == "Modify")
        {
            btnUpdate.Text = "修改";
        }
        else if (Action == "Add")
        {
            btnUpdate.Text = "增加";
        }
        else if (Action == "Delete")
        {
            btnAction();
            return;
        }

        if (!IsPostBack)
        {
            BindTreeDrop("");
        }
    }


    //添加按扭事件
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        btnAction();
    }

    /// <summary>
    /// 绑定栏目树型下拉列表
    /// </summary>    
    protected void BindTreeDrop(string str)
    {
        this.ddlParent.DataValueField = "columnID";
        this.ddlParent.DataTextField = "columnName";
        Whir.Common.BindHelper.BindDropDownList(this.ddlParent, "Whir_Column", "0", str, "-- 导航栏目 --");
    }

    /// <summary>
    /// 删除栏目编号
    /// </summary>
    private void DeleteColumn(string columnID)
    {
        Whir.SQLServerDAL.Whir_Column bll = new Whir.SQLServerDAL.Whir_Column();
        Whir.Model.Whir_Column model = bll.GetModel(int.Parse(columnID));
        if (model != null)
        {
            bll.Delete(int.Parse(columnID));
        }

        //修改角色表之栏目id
        RoleHelper.UpdateColumnIDs(columnID);
    }

    /// <summary>
    /// 添加方法
    /// </summary>
    private void btnAction()
    {
        int columnID = 0;

        switch (Action)
        {
            case "Add":
                columnID = AddColumn();
                Response.Clear();
                if (columnID == -1)
                    Response.Write("<script>alert('添加栏目失败，请正确填写栏目格式！');</script>");
                Response.Write("<script>parent.location='ColumnNewList.aspx?op=" + Action + "';</script>");
                break;
        }

        Response.End();
        return;
    }

    /// <summary>
    /// 添加栏目
    /// </summary>
    /// <returns></returns>
    private int AddColumn()
    {
        string addColumns = "";
        try
        {
            Whir.Model.Whir_Column parentModel = new Whir.BLL.Whir_Column().GetModel(int.Parse(ddlParent.SelectedValue));


            string columns = txtColumns.Text;

            columns = columns.Replace("\r\n", "|").Replace("－", "-"); //利用分行符号把栏目区分
            string[] columnCount = columns.Split('|');

            //记录当前栏目级别与栏目编号
            Dictionary<int, int> dic = new Dictionary<int, int>();
            //记录当前级别的个数，用于排序的
            Dictionary<int, int> dicCount = new Dictionary<int, int>();

            for (int i = 0; i < columnCount.Length; i++)
            {
                if (columnCount[i].Trim() != string.Empty)
                {
                    int level = 0;      //当前栏目的级别，根据“-”的个数定义
                    int count = 1;

                    Whir.Model.Whir_Column model = new Whir.Model.Whir_Column();

                    string columnName = columnCount[i];
                    if (columnName.Contains("-"))
                    {
                        //获取“-”出现的个数，出现的次数代表级别
                        level = GetCount(columnCount[i], "-");

                        int parentID = 0;
                        //获取该级别是否存在
                        if (!dic.TryGetValue(level - 1, out parentID))
                        {
                            throw new Exception();
                        }

                        if (dicCount.ContainsKey(level))
                            dicCount[level] = dicCount[level] + 1;
                        else
                            dicCount[level] = 1;

                        model.parentID = parentID;
                        model.columnName = columnCount[i].Replace("-", "").Trim();
                    }
                    else //添加一级子栏目
                    {
                        level = 0;

                        if (dicCount.ContainsKey(level))
                            dicCount[level] = dicCount[level] + 1;
                        else
                            dicCount[level] = GetMxaSort(ddlParent.SelectedValue);

                        model.parentID = int.Parse(this.ddlParent.SelectedValue);
                        model.columnName = columnCount[i];
                    }

                    model.formID = "-1";
                    model.columnMark = "Whir_" + DateTime.Now.ToString();
                    model.moduleMark = "";
                    model.OperatePage = "";
                    model.param = "";
                    model.sort = dicCount[level];
                    model.url = "";
                    model.pic = "";
                    model.metaTitle = "";
                    model.metaKey = "";
                    model.metaDesc = "";
                    model.listTemp = "";
                    model.defaultTemp = "";
                    model.contentTemp = "";
                    model.isCreateHtml = true;
                    model.isUse = true;

                    model.createDate = DateTime.Now;
                    model.createUserID = RoleHelper.GetAdminID();
                    model.updateDate = model.createDate;
                    model.updateUserID = model.createUserID;
                    model.directory = parentModel != null ? parentModel.directory : "cn";
                    model.IsSinglePage = false;

                    int cloumnID = new Whir.SQLServerDAL.Whir_Column().Add(model);

                    //把当前栏目编号所对应的级别添加到记录中
                    //当前级别存在
                    if (dic.ContainsKey(level))
                        dic[level] = cloumnID;
                    else
                        dic.Add(level, cloumnID);

                    //把当前栏目记录，回滚的时候用到
                    addColumns += cloumnID + ",";
                }
            }
            return int.Parse(this.ddlParent.SelectedValue);
        }
        catch
        {
            if (addColumns.Trim() != string.Empty)
            {
                string[] strTemp = addColumns.Split(',');
                for (int i = 0; i < strTemp.Length; i++)
                {
                    if (strTemp[i] != string.Empty)
                        DeleteColumn(strTemp[i]);
                }
            }

            return -1;
        }
    }

    /// <summary>
    /// 获取该栏目的父级栏目的子栏目个数
    /// </summary>
    /// <param name="parentID">栏目编号</param>
    protected int GetMxaSort(string parentID)
    {
        string sql = String.Format("SELECT MAX(sort) + 1 FROM Whir_Column WHERE parentID = {0}", parentID);
        object obj = Whir.SQLServerDAL.DbHelperSQL.GetSingle(sql);

        return obj != null ? Convert.ToInt32(obj) : 1;
    }

    /// <summary>
    /// 获取字符串中字符出现的个数
    /// </summary>
    /// <param name="str1">字符串</param>
    /// <param name="str2">字符</param>
    /// <returns>字符出现的个数</returns>
    protected int GetCount(string str1, string str2)
    {
        return (str1.Length - str1.Replace(str2, "").Length);
    }
}
